<template>
  <div class="doctors-container">
    <div class="page-header">
      <h2 class="page-title">
        <el-icon><UserFilled /></el-icon>
        在线医生管理
      </h2>
      <el-button type="primary" @click="handleAdd">
        <el-icon><Plus /></el-icon>
        添加医生
      </el-button>
    </div>

    <!-- Search and Filter -->
    <div class="search-bar">
      <el-input
        v-model="searchQuery"
        placeholder="搜索医生姓名或专业"
        class="search-input"
        clearable
        @clear="handleSearch"
        @input="handleSearch"
      >
        <template #prefix>
          <el-icon><Search /></el-icon>
        </template>
      </el-input>
      <el-select v-model="statusFilter" placeholder="状态筛选" @change="handleSearch">
        <el-option label="全部" value="" />
        <el-option label="在线" value="online" />
        <el-option label="离线" value="offline" />
        <el-option label="忙碌" value="busy" />
      </el-select>
    </div>

    <!-- Doctors Table -->
    <el-table :data="filteredDoctors" style="width: 100%" v-loading="loading">
      <el-table-column prop="avatar" label="头像" width="80">
        <template #default="{ row }">
          <el-avatar :size="40" :src="row.avatar" />
        </template>
      </el-table-column>
      <el-table-column prop="name" label="姓名" width="120" />
      <el-table-column prop="title" label="职称" width="120" />
      <el-table-column prop="department" label="科室" width="120" />
      <el-table-column prop="specialty" label="专长" />
      <el-table-column prop="status" label="状态" width="100">
        <template #default="{ row }">
          <el-select
            v-model="row.status"
            size="small"
            @change="handleStatusChange(row)"
            style="width: 90px"
          >
            <el-option label="在线" value="online" />
            <el-option label="离线" value="offline" />
            <el-option label="忙碌" value="busy" />
          </el-select>
        </template>
      </el-table-column>
      <el-table-column prop="rating" label="评分" width="100">
        <template #default="{ row }">
          <el-rate v-model="row.rating" disabled show-score />
        </template>
      </el-table-column>
      <el-table-column label="操作" width="200" fixed="right">
        <template #default="{ row }">
          <el-button-group>
            <el-button type="primary" size="small" @click="handleEdit(row)">
              编辑
            </el-button>
            <el-button type="success" size="small" @click="handleSchedule(row)">
              排班
            </el-button>
            <el-button type="danger" size="small" @click="handleDelete(row)">
              删除
            </el-button>
          </el-button-group>
        </template>
      </el-table-column>
    </el-table>

    <!-- Pagination -->
    <div class="pagination-container">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 50, 100]"
        :total="total"
        layout="total, sizes, prev, pager, next"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- Add/Edit Dialog -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'add' ? '添加医生' : '编辑医生'"
      width="600px"
    >
      <el-form
        ref="formRef"
        :model="doctorForm"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="姓名" prop="name">
          <el-input v-model="doctorForm.name" />
        </el-form-item>
        <el-form-item label="职称" prop="title">
          <el-input v-model="doctorForm.title" />
        </el-form-item>
        <el-form-item label="科室" prop="department">
          <el-input v-model="doctorForm.department" />
        </el-form-item>
        <el-form-item label="专长" prop="specialty">
          <el-input type="textarea" v-model="doctorForm.specialty" />
        </el-form-item>
        <el-form-item label="头像" prop="avatar">
          <el-input v-model="doctorForm.avatar" placeholder="请输入头像图片URL" />
        </el-form-item>
        <el-form-item label="简介" prop="introduction">
          <el-input type="textarea" v-model="doctorForm.introduction" rows="4" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="doctorForm.status" placeholder="请选择状态">
            <el-option label="在线" value="online" />
            <el-option label="离线" value="offline" />
            <el-option label="忙碌" value="busy" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- Schedule Dialog -->
    <el-dialog
      v-model="scheduleDialogVisible"
      title="排班管理"
      width="800px"
    >
      <el-calendar v-model="currentDate">
        <template #dateCell="{ data }">
          <div class="schedule-cell">
            <p>{{ data.day.split('-').slice(1).join('-') }}</p>
            <el-select
              v-model="scheduleData[data.day]"
              placeholder="选择状态"
              size="small"
            >
              <el-option label="休息" value="off" />
              <el-option label="上午" value="morning" />
              <el-option label="下午" value="afternoon" />
              <el-option label="全天" value="full" />
            </el-select>
          </div>
        </template>
      </el-calendar>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="scheduleDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="saveSchedule">保存排班</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, UserFilled, Search } from '@element-plus/icons-vue'

export default {
  name: 'DoctorsManagement',
  setup() {
    const loading = ref(false)
    const doctors = ref([])
    const searchQuery = ref('')
    const statusFilter = ref('')
    const currentPage = ref(1)
    const pageSize = ref(10)
    const total = ref(0)
    const dialogVisible = ref(false)
    const dialogType = ref('add')
    const scheduleDialogVisible = ref(false)
    const currentDate = ref(new Date())
    const scheduleData = ref({})
    const currentDoctor = ref(null)

    const doctorForm = ref({
      name: '',
      title: '',
      department: '',
      specialty: '',
      avatar: '',
      introduction: '',
      status: 'online'
    })

    const rules = {
      name: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
      title: [{ required: true, message: '请输入职称', trigger: 'blur' }],
      department: [{ required: true, message: '请输入科室', trigger: 'blur' }],
      specialty: [{ required: true, message: '请输入专长', trigger: 'blur' }],
      status: [{ required: true, message: '请选择状态', trigger: 'change' }]
    }

    const filteredDoctors = computed(() => {
      let result = doctors.value
      if (searchQuery.value) {
        const query = searchQuery.value.toLowerCase()
        result = result.filter(doctor => 
          doctor.name.toLowerCase().includes(query) ||
          doctor.specialty.toLowerCase().includes(query)
        )
      }
      if (statusFilter.value) {
        result = result.filter(doctor => doctor.status === statusFilter.value)
      }
      return result
    })

    const getStatusType = (status) => {
      const types = {
        online: 'success',
        offline: 'info',
        busy: 'warning'
      }
      return types[status] || 'info'
    }

    const getStatusText = (status) => {
      const texts = {
        online: '在线',
        offline: '离线',
        busy: '忙碌'
      }
      return texts[status] || '未知'
    }

    const fetchDoctors = async () => {
      loading.value = true
      try {
        const response = await fetch('http://localhost:3000/doctors')
        const data = await response.json()
        doctors.value = data.map(doctor => ({
          ...doctor,
          rating: 4.5,
          status: doctor.status === 'active' ? 'online' : 
                 doctor.status === 'busy' ? 'busy' : 'offline'
        }))
        total.value = data.length
      } catch (error) {
        console.error('获取医生列表失败:', error)
        ElMessage.error('获取医生列表失败')
      } finally {
        loading.value = false
      }
    }

    const handleAdd = () => {
      dialogType.value = 'add'
      doctorForm.value = {
        name: '',
        title: '',
        department: '',
        specialty: '',
        avatar: '',
        introduction: '',
        status: 'online'
      }
      dialogVisible.value = true
    }

    const handleEdit = (row) => {
      dialogType.value = 'edit'
      doctorForm.value = { ...row }
      dialogVisible.value = true
    }

    const handleDelete = (row) => {
      ElMessageBox.confirm(
        '确定要删除该医生吗？',
        '警告',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).then(async () => {
        try {
          const response = await fetch(`http://localhost:3000/doctors/${row.id}`, {
            method: 'DELETE'
          })
          
          if (!response.ok) {
            throw new Error('删除失败')
          }
          
          ElMessage.success('删除成功')
          fetchDoctors()
        } catch (error) {
          console.error('删除失败:', error)
          ElMessage.error('删除失败')
        }
      })
    }

    const handleSchedule = (row) => {
      currentDoctor.value = row
      scheduleDialogVisible.value = true
      // TODO: Fetch existing schedule data
    }

    const saveSchedule = async () => {
      try {
        // 由于db.json中没有schedules表，这里暂时只做提示
        ElMessage.success('排班功能开发中...')
        scheduleDialogVisible.value = false
      } catch (error) {
        console.error('保存排班失败:', error)
        ElMessage.error('保存排班失败')
      }
    }

    const handleStatusChange = async (row) => {
      try {
        const response = await fetch(`http://localhost:3000/doctors/${row.id}`, {
          method: 'PUT',
          headers: {
            'Content-Type': 'application/json'
          },
          body: JSON.stringify({
            ...row,
            status: row.status === 'online' ? 'active' : 
                   row.status === 'busy' ? 'busy' : 'inactive'
          })
        })
        
        if (!response.ok) {
          throw new Error('更新状态失败')
        }
        
        ElMessage.success('状态更新成功')
      } catch (error) {
        console.error('更新状态失败:', error)
        ElMessage.error('更新状态失败')
        // 恢复原状态
        row.status = row.status === 'online' ? 'offline' : 'online'
      }
    }

    const handleSubmit = async () => {
      try {
        const url = dialogType.value === 'add' 
          ? 'http://localhost:3000/doctors'
          : `http://localhost:3000/doctors/${doctorForm.value.id}`
        const method = dialogType.value === 'add' ? 'POST' : 'PUT'
        
        const response = await fetch(url, {
          method,
          headers: {
            'Content-Type': 'application/json'
          },
          body: JSON.stringify({
            ...doctorForm.value,
            status: doctorForm.value.status === 'online' ? 'active' : 'inactive'
          })
        })
        
        if (!response.ok) {
          throw new Error('操作失败')
        }
        
        ElMessage.success(dialogType.value === 'add' ? '添加成功' : '更新成功')
        dialogVisible.value = false
        fetchDoctors()
      } catch (error) {
        console.error('操作失败:', error)
        ElMessage.error(dialogType.value === 'add' ? '添加失败' : '更新失败')
      }
    }

    const handleSearch = () => {
      currentPage.value = 1
      fetchDoctors()
    }

    const handleSizeChange = (val) => {
      pageSize.value = val
      fetchDoctors()
    }

    const handleCurrentChange = (val) => {
      currentPage.value = val
      fetchDoctors()
    }

    onMounted(() => {
      fetchDoctors()
    })

    return {
      loading,
      doctors,
      searchQuery,
      statusFilter,
      currentPage,
      pageSize,
      total,
      dialogVisible,
      dialogType,
      scheduleDialogVisible,
      currentDate,
      scheduleData,
      doctorForm,
      rules,
      filteredDoctors,
      getStatusType,
      getStatusText,
      handleAdd,
      handleEdit,
      handleDelete,
      handleSchedule,
      saveSchedule,
      handleStatusChange,
      handleSubmit,
      handleSearch,
      handleSizeChange,
      handleCurrentChange
    }
  }
}
</script>

<style scoped>
.doctors-container {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-title {
  display: flex;
  align-items: center;
  gap: 8px;
  margin: 0;
  color: black;
}

.search-bar {
  display: flex;
  gap: 16px;
  margin-bottom: 20px;
}

.search-input {
  width: 300px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.avatar-uploader {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  width: 178px;
  height: 178px;
}

.avatar-uploader:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
  line-height: 178px;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
}

.schedule-cell {
  height: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 4px;
}

.schedule-cell p {
  margin: 0;
  font-size: 12px;
}
</style> 